package com.lmuse.xmr.foodspotting.ui.upload;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.andreabaccega.widget.FormEditText;
import com.lmuse.xmr.foodspotting.FoodApplication;
import com.lmuse.xmr.foodspotting.R;
import com.lmuse.xmr.foodspotting.constants.App;
import com.lmuse.xmr.foodspotting.db.Contract;
import com.lmuse.xmr.foodspotting.db.RecipePresenterImpl;
import com.lmuse.xmr.foodspotting.model.Recipe;
import com.lmuse.xmr.foodspotting.util.CommonUtil;
import com.lmuse.xmr.foodspotting.util.ImageUtils;
import com.lmuse.xmr.foodspotting.util.SDCardUtil;
import com.sendtion.xrichtext.RichTextEditor;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import me.iwf.photopicker.PhotoPicker;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class UploadActivity extends AppCompatActivity implements RichTextEditor.OnDeleteImageListener, Contract.RecipeView{
    private static final String TAG = "UploadActivity";

    private FoodApplication foodApplication;

    private ImageView coverView;
    private Button changeCover;
    private Button upload;
    private ImageButton insertPic;
    private FormEditText inputTitle;
    private RichTextEditor inputContent;
    private Spinner labelSpinner;
    private ArrayAdapter adapter;
    private Subscription subsInsert;
    private ProgressDialog insertDialog;
    private ProgressDialog uploadDialog;

    private Contract.RecipePresenter recipePresenter;

    private BmobFile cover;
    private String coverPath;
    private List<String> imgUrlList; //用来记录插入到content中的图片上传之后的url集合
    private List<RichTextEditor.EditData> editList; //富文本编辑器中的内容集合
    private int imgCount = 0; //记录内容中的图片个数
    private String title;
    private String content;
    private String[] label = {"请选择标签","早餐","午餐","晚餐","家常菜","蒸菜","炖菜","炒菜","素食",
            "瘦身餐","汤类","主食","川菜","湘菜","东北菜","清真菜","日本料理","韩国料理","甜点","西点"};
    private List<String> labelList;
    private boolean allValid = true; //输入合法性
    private int labelSelected = 0; //选择的标签
    private int photoPickerMode;  //谁调用图片的选择: :0 Cover 1:Content

    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        recipePresenter = new RecipePresenterImpl(this);
        initView();
    }

    void initView() {
        foodApplication = (FoodApplication) this.getApplicationContext();

        coverView = (ImageView) findViewById(R.id.img_upload_cover);
        inputTitle = (FormEditText) findViewById(R.id.et_input_title);
        inputContent = (RichTextEditor) findViewById(R.id.et_new_content);
        labelSpinner = (Spinner) findViewById(R.id.sp_label);
        changeCover = (Button) findViewById(R.id.btn_change_cover);
        upload = (Button) findViewById(R.id.btn_upload);
        insertPic = (ImageButton) findViewById(R.id.imgBtn_insertPicture);
        changeCover.setOnClickListener(new ButtonClickListener());
        insertPic.setOnClickListener(new ButtonClickListener());

        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);

        uploadDialog = new ProgressDialog(this);
        uploadDialog.setMessage("正在上传");
        uploadDialog.setCanceledOnTouchOutside(false);

        labelList = new ArrayList<>();
        setLabelData();
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, labelList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        labelSpinner.setAdapter(adapter);
        labelSpinner.setOnItemSelectedListener(new ItemSelectedListener());
        upload.setOnClickListener(new ButtonClickListener());
        //        upload.setIndeterminateProgressMode(true);   // turn on indeterminate progress
    }

    class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_change_cover:

                    callGallery(1);
                    break;
                case R.id.imgBtn_insertPicture:

                    callGallery(5);
                    break;
                case R.id.btn_upload:
                    //                    upload.setProgress(50); //开始转圈圈 set progress > 0 & < 100 to display indeterminate progress
                    checkInputValid();
                    break;
            }
        }
    }

    class ItemSelectedListener implements Spinner.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            labelSelected = i;
//            Toast.makeText(UploadActivity.this, "选择了" + labelList.get(labelSelected), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

    /**
     * 输入合法性检查
     */
    void checkInputValid() {
        FormEditText[] allFields = {inputTitle};

        for (FormEditText field: allFields) {
            allValid = field.testValidity() && allValid;
        }

        if (allValid) {  //已输入标题
            title = inputTitle.getText().toString();
            if ( labelSelected != 0) { //已选择标签

                if (coverPath != null) { //已选择封面
                    if (!isContentEmpty()) { //已输入内容

                        uploadDialog.show();
                        //上传封面拿到BmobFile
                        recipePresenter.uploadImgFile(coverPath);
                    } else {
                        allValid = true;
                        Toast.makeText(this, "内容不能为空！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    allValid = true;
                    Toast.makeText(this, "封面图未添加！", Toast.LENGTH_SHORT).show();
                }
            }else {
                allValid = true;
                Toast.makeText(this, "标签未选择！", Toast.LENGTH_SHORT).show();
            }
        } else {
            allValid = true;
            // EditText are going to appear with an exclamation mark and an explicative message.
        }
    }

    /**
     * 装载标签数据
     */
    private void setLabelData() {
        for (int i = 0; i < label.length; i++) {
            labelList.add(label[i]);
        }
    }

    /**
     * 调用图库选择器
     * @param amount
     */
    private void callGallery(int amount){
        //        //调用系统图库
        //        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");// 相片类型
        //        startActivityForResult(intent, 1);

        switch (amount) {
            case 1:
                foodApplication.setPhotoPickerFlag(App.PHOTO_PICKER_COVER);
                break;
            case 5:
                foodApplication.setPhotoPickerFlag(App.PHOTO_PICKER_CONTENT);
                break;
        }
        //调用第三方图库选择
        PhotoPicker.builder()
//                .setPhotoCount(amount)//可选择图片数量
                .setPhotoCount(1)//可选择图片数量
                .setShowCamera(true)//是否显示拍照按钮
                .setShowGif(false)//是否显示动态图
                .setPreviewEnabled(false)//是否可以预览
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {

                switch (requestCode) {
                    case 1:
                        //处理调用系统图库
                        break;
                    case PhotoPicker.REQUEST_CODE:
                        if (foodApplication.getPhotoPickerFlag() == App.PHOTO_PICKER_COVER) {

                            //处理takePhoto的图片,放入封面
                            insertCoverImage(data);
                        }else if (foodApplication.getPhotoPickerFlag() == App.PHOTO_PICKER_CONTENT) {

                            //处理photopicker的图片，异步方式插入Content图片
                            insertImagesSync(data);
                        }
                        break;
                }
            }
        }
    }

    /**
     * 处理封面图片
     * @param data
     */
    private void insertCoverImage(final Intent data) {

        int width = CommonUtil.getScreenWidth(UploadActivity.this);
        int height = CommonUtil.getScreenHeight(UploadActivity.this);
        ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
        //可以同时插入多张图片
        for (String imagePath : photos) {
            Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, width, height);//压缩图片
            coverPath = SDCardUtil.saveToSdCard(bitmap);
            Log.i(TAG, "insertCoverImage: " + coverPath);
            coverView.setImageBitmap(bitmap);
        }
    }

    /**
     * 异步方式插入图片
     * @param data
     */
    private void insertImagesSync(final Intent data) {
        insertDialog.show();

        subsInsert = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try{
                    inputContent.measure(0, 0);
                    int width = CommonUtil.getScreenWidth(UploadActivity.this);
                    int height = CommonUtil.getScreenHeight(UploadActivity.this);
                    ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    //可以同时插入多张图片
                    for (String imagePath : photos) {
                        //Log.i("NewActivity", "###path=" + imagePath);
                        Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, width, height);//压缩图片
                        //bitmap = BitmapFactory.decodeFile(imagePath);
                        imagePath = SDCardUtil.saveToSdCard(bitmap);
//                        Log.i(TAG, "###imagePath="+imagePath);
                        subscriber.onNext(imagePath);
                    }
                    subscriber.onCompleted();
                }catch (Exception e){
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                        inputContent.addEditTextAtIndex(inputContent.getLastIndex(), " ");
                        Toast.makeText(UploadActivity.this, "图片插入成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        Toast.makeText(UploadActivity.this, "图片插入失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(String imagePath) {
                        inputContent.insertImage(imagePath, inputContent.getMeasuredWidth());
                    }
                });
    }

    /**
     * 判断输入内容是否为空
     * @return boolean true 为空
     */
    private boolean isContentEmpty() {
        editList = inputContent.buildEditData();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                return false;
            } else if (itemData.imagePath != null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 将content中的图片上传之后拿到urlList
     */
    private void getImgUrlList() {
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.imagePath != null) {
                imgCount ++ ;
            }
        }
        if (imgCount != 0) {
            //本地图片路径数组
            String[] filePaths = new String[imgCount];
            int i = 0;
            for (RichTextEditor.EditData itemData : editList) {
                if (itemData.imagePath != null) {
                    filePaths[i] = itemData.imagePath;
                    i++;
                }
            }
            recipePresenter.uploadImgFile(filePaths);
        }else {
            content = getContentData(null);
            recipePresenter.addRecipe(title, cover.getFileUrl(), labelList.get(labelSelected), content);
        }
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     * @return String Content
     * @param urls
     */
    private String getContentData(List<String> urls) {
        int i = 0;
        StringBuffer content = new StringBuffer();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
            } else if (itemData.imagePath != null) {
                content.append("<img src=\"").append(urls.get(i)).append("\"/>");
            }
        }
        return content.toString();
    }

    @Override
    public void onDeleteImage(String s) {
        boolean isOK = SDCardUtil.deleteFile(s);
        if (isOK){
            Toast.makeText(UploadActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onUploadingImg(Integer value) {

    }

    @Override
    public void onUploadingImg(int curIndex, int curPercent, int total, int totalPercent) {
        //todo 加个progress吗？
    }

    @Override
    public void onUploadImgSuccess(BmobFile cover) {
        this.cover = cover;
        //上传内容图片拿到图片url集合
        getImgUrlList();
    }

    @Override
    public void onUploadImgSuccess(List<String> urls) {
        imgUrlList = urls;
        content = getContentData(urls);

        recipePresenter.addRecipe(title, cover.getFileUrl(), labelList.get(labelSelected), content);
    }

    @Override
    public void onUploadImgFailed(String msg) {
        if (uploadDialog != null) {
            uploadDialog.cancel();
        }
        Toast.makeText(UploadActivity.this, msg , Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAddRecipeSuccess() {
        if (uploadDialog != null) {
            uploadDialog.cancel();
        }
        Toast.makeText(UploadActivity.this, "上传菜谱成功！", Toast.LENGTH_SHORT).show();
        this.finish();
    }

    @Override
    public void onAddRecipeFailed(String msg) {
        if (uploadDialog != null) {
            uploadDialog.cancel();
        }
        Toast.makeText(UploadActivity.this, "上传菜谱失败！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onQueryRecipeSuccess(Recipe recipe) {

    }

    @Override
    public void onQueryRecipeSuccess(List<Recipe> recipeList) {

    }

    @Override
    public void onQueryRecipeFailed(String msg) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// && event.getAction() == KeyEvent.ACTION_DOWN
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出编辑", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onQueryKeySuccess(List<Recipe> recipeKeyList) {

    }

    @Override
    public void onQueryKeyFailed(String msg) {

    }

    @Override
    public void onDeleteRecipeSuccess() {

    }

    @Override
    public void onDeleteRecipeFailed(String msg) {

    }
}